package cn.crce.cloud9.comp;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

/**
 * @author OnCloud9
 * @description
 * @project NRCE-TEST
 * @date 2022年09月13日 下午 09:59
 */
public class Case45 extends JFrame implements ActionListener {
    JTextField nval = new JTextField(10);
    //**********Found**********
    JButton calcBtn = new JButton("计算");
    JTextArea result = new JTextArea(10, 20);

    void initFrame() {
        Container content = getContentPane();
        JPanel calcPanel = new JPanel();
        calcPanel.add(new JLabel("N值"));
        //**********Found**********
        calcPanel.add(nval);
        calcPanel.add(calcBtn);
        content.add(calcPanel, "North");
        //**********Found**********
        calcBtn.addActionListener(this);
        content.add(result, "Center");
        result.setEditable(false);
    }

    public Case45() {
        super("计算素数");
        setSize(500, 200);
        initFrame();
        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void actionPerformed(ActionEvent e) {
        if (e.getSource() == calcBtn) {
            int N = Integer.parseInt(nval.getText());
            int[] prime = new int[N / 3 + 2];
            prime[0] = 2;
            prime[1] = 3;
            int k = 2;
            for (int m = 5; m <= N; m += 2) {
                int j = 1, isprime = 1;
                int kk = Math.round((float) Math.sqrt(m));
                while (prime[j] <= kk) {
                    if (m % prime[j] == 0) {
                        //**********Found**********
                        isprime = 0;
                        break;
                    } else
                        //**********Found**********
                        j++;
                }
                if (isprime == 1) prime[k++] = m;
            }
            //**********Found**********
            String str = "Total prime number: " + k;
            result.setText("");
            result.append(str);
        }
    }

    public static void main(String[] args) {
        new Case45();
    }
}
